shopt -s expand_aliases

SCRIPT_PATH=${SCRIPT_PATH:-"$0"}
SCRIPT_DIR=`dirname "$SCRIPT_PATH"`
SCRIPT_DIR=`cd "$SCRIPT_DIR"; pwd`
SCRIPT_PATH="$SCRIPT_DIR/`basename "$SCRIPT_PATH"`"
CONFIG_PATH="$SCRIPT_DIR/svncc.cfg"

if [ "$OSTYPE" == "cygwin" ]
then
    IS_CYGWIN="true"
    CONFIG_PATH="`cygpath -a "$CONFIG_PATH"`"
fi

. "$CONFIG_PATH"

if [ ! -z "$IS_CYGWIN" ]
then
    SCRIPT_PATH="`cygpath -a "$SCRIPT_PATH"`"
    SCRIPT_DIR="`cygpath -a "$SCRIPT_DIR"`"
    LOG_DIR="`cygpath -a "$LOG_DIR"`"
fi

SVNCC_HOME=${SVNCC_HOME:-"$SCRIPT_DIR"}
LOG_FILE_SUFFIX=${LOG_FILE_SUFFIX:-".log"}
LOG_FILE_NAME=${LOG_FILE_NAME:-"${SCRIPT_PATH##*/}$LOG_FILE_SUFFIX"}
LOG_FILE=${LOG_FILE:-"$LOG_DIR/$LOG_FILE_NAME"}

if [ -d "${LOG_DIR}" ]
then
    rm -f "$LOG_FILE"
else 
    mkdir -p "${LOG_DIR}"
fi

function log_message {
    local caller="$1"
    shift
    echo "$caller| $*" >> "$LOG_FILE"
}

function echo_err {
    echo "$*" >&2
}

function success {
    [[ $DELETE_LOG_ON_SUCCESS == true ]] && rm -f "$LOG_FILE"
    exit 0
}

function fail {
    local ec
    
    if [ -z "$1" ]
    then
        local ec="1"
        echo "Script failed. Log file:" >&2
    else
        local ec="$1"
        echo_err "Script failed with exit code $ec. Log file:"
    fi
    
    cat "$LOG_FILE" >&2
    [[ $DELETE_LOG_ON_FAILURE == true ]] && rm -f "$LOG_FILE"
    exit $ec
}

function execute_command {
    local caller="$1"
    local cmd="\"$2\""
    shift 2
    local args_count=${#}
    local i
    
    for ((i = 0; i < args_count; i++))
    do
        cmd="${cmd} \"${1}\""
        shift 1
    done
    
    log_message "$caller" "cmd> $cmd"
    # eval $cmd 2>&1 | tee -a "$LOG_FILE"
    # EXIT_CODE=${PIPESTATUS[((${#PIPESTATUS[@]} - 2))]}
    eval $cmd 2>> "$LOG_FILE"
    EXIT_CODE=$?
    return $EXIT_CODE
}

function try_execute_command {
    local caller="$1"
    local cmd="\"$2\""
    shift 2
    local args_count=${#}
    local i
    
    for ((i = 0; i < args_count; i++))
    do
        cmd="${cmd} \"${1}\""
        shift 1
    done
    
    log_message "$caller" "cmd> $cmd"
    # eval $cmd 2>&1 | tee -a "$LOG_FILE"
    # EXIT_CODE=${PIPESTATUS[((${#PIPESTATUS[@]} - 2))]}
    eval $cmd 2>> "$LOG_FILE"
    EXIT_CODE=$?
    [[ $EXIT_CODE != 0 ]] && fail $EXIT_CODE
}

function trim {
    sed 's/^[ \t\r\n]*//; s/[ \t\r\n]*$//' <<< "$*"
}

function cc_view_path {
    echo "$CC_VIEW_DIR/`trim $1`"
}

function array_contains {
    eval "local size=\${#$1[*]}"
    local i
    local item
          
    for (( i = 0 ; i < $size; i++ ))
    do
        eval "item=\"\${$1[$i]}\""
        if [ "$item" == "$2" ]
        then
            echo "true"
            return 0
        fi
    done
    
    echo "false"
    return 1
}

function array_to_args {
    eval "local size=\${#$1[*]}"
    local i
          
    for (( i = 0 ; i < $size; i++ ))
    do
        echo -n " \""
        eval "echo -n "\${$1[$i]}\"\"
        echo -n "\""
    done
}